import React, { ReactElement, useContext, useMemo, useState } from 'react';
import { View, Text, ScrollView } from 'react-native';
import { filter, splitEvery } from 'ramda';
import LinearGradient from 'react-native-linear-gradient';

import styles from './style';
import { phonePx } from '../../../../util/adapt';
import { Store } from '../../reducer';
import {
  CLASS_ROOM_RIGHT_SCALE,
  LIVE_AREA,
  LIVE_AREA_HEIGHT,
  PPTType,
  RoundType,
  UserRole
} from '../../constant';
import { LiveUser } from '../../types';
import UserLive from './components/UserLive';
import { getUserInfo } from '../../../../store/user';
import CurrentUser from './components/CurrentUser';
import Corner from '../Graph/Corner';
import { GRADIENT_BLACK_BACKGROUND_COLOR } from '../../../../constant/color';
import { isIOS } from '../../../../constant';

export default (): ReactElement => {
  const [currentPage, setCurrentPage] = useState(0);
  const { state } = useContext(Store);
  const {
    users,
    isJoinedChannel,
    showLiveEnd,
    currentPPT,
    teacherName,
    parentStudentId
  } = state;

  const { userId: localUserId, role } = getUserInfo();
  const students = filter(
    (item: LiveUser): boolean =>
      item.userRole === UserRole.Student &&
      item.userId !== localUserId &&
      item.userId !== parentStudentId
  )(users);
  const studentPageList = splitEvery(4, students);

  const currentUser = users.find(
    (u): boolean => u.userId === localUserId && role === UserRole.Student
  );
  const parentStudentUser = users.find(
    (u): boolean => u.userId === parentStudentId && role === UserRole.Parent
  );

  const { type, round } = currentPPT;
  let isRestVideo = false;
  if (round) {
    const { roundInfoVideo, roundType } = round;
    isRestVideo =
      roundType === RoundType.Video && roundInfoVideo && roundInfoVideo.isRest;
  }

  const isVideo = type === PPTType.Video && !isRestVideo;

  return useMemo((): ReactElement => {
    if (!isJoinedChannel) return <View />;
    return (
      <View style={styles.videoArea}>
        <View style={styles.teacher}>
          <View style={styles.leftLine} />
          <View style={styles.topLine} />
          <View style={styles.rightLine} />
          <View style={styles.bottomLine} />
          {isVideo && (
            <LinearGradient
              colors={GRADIENT_BLACK_BACKGROUND_COLOR}
              style={styles.nameContent}
              start={{ x: 0.0, y: 1.0 }}
              end={{ x: 0.0, y: 0.0 }}
            >
              <Text style={styles.name}>{teacherName}</Text>
            </LinearGradient>
          )}
          <Corner
            style={styles.corner}
            width={LIVE_AREA - phonePx(8) * CLASS_ROOM_RIGHT_SCALE}
            height={LIVE_AREA_HEIGHT - phonePx(6) * CLASS_ROOM_RIGHT_SCALE}
            dia={phonePx(4) * CLASS_ROOM_RIGHT_SCALE}
          />
        </View>
        <View style={styles.content}>
          <View style={styles.kidContent}>
            <View style={styles.list}>
              <ScrollView
                horizontal
                showsHorizontalScrollIndicator={false}
                pagingEnabled
                onMomentumScrollEnd={(event): void => {
                  if (event.nativeEvent.contentOffset.x === 0) {
                    setCurrentPage(0);
                  } else {
                    setCurrentPage(1);
                  }
                }}
              >
                {studentPageList.map(
                  (studentList, pageIndex): ReactElement => (
                    <View style={styles.card}>
                      {studentList.map(
                        ({
                          userId,
                          goldCoinNum,
                          haveAnswer,
                          userNickName
                        }): ReactElement => {
                          if (showLiveEnd) {
                            return <View />;
                          }
                          const useTextureView =
                            !isIOS && // android 支持TextureView
                            studentPageList.length > 1 && // 存在多页
                            pageIndex !== studentPageList.length - 1; // 除了最后一页，其他页都使用TextureView
                          return (
                            <UserLive
                              key={userId}
                              userId={userId}
                              goldCoinNum={goldCoinNum}
                              haveAnswer={haveAnswer || false}
                              name={userNickName}
                              useTextureView={useTextureView}
                            />
                          );
                        }
                      )}
                    </View>
                  )
                )}
              </ScrollView>
            </View>
            {students.length > 4 && (
              <View style={styles.pageContent}>
                <View
                  style={[
                    styles.current,
                    currentPage === 0 ? styles.left : styles.right
                  ]}
                />
              </View>
            )}
          </View>
          {parentStudentUser && (
            <UserLive
              key={parentStudentUser.userId}
              userId={parentStudentUser.userId}
              goldCoinNum={parentStudentUser.goldCoinNum}
              haveAnswer={parentStudentUser.haveAnswer || false}
              name={parentStudentUser.userNickName}
              style={styles.parent}
            />
          )}
          {currentUser && <CurrentUser {...currentUser} />}
        </View>
      </View>
    );
  }, [
    isJoinedChannel,
    isVideo,
    teacherName,
    studentPageList,
    students.length,
    currentPage,
    parentStudentUser,
    currentUser,
    showLiveEnd
  ]);
};
